package product.exception;


import lombok.extern.slf4j.Slf4j;
import com.feign.exception.BizCodeEnum;
import com.feign.utils.R;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * jsr303集中校验异常类
 */
@Slf4j
@RestControllerAdvice(basePackages = "product.controller")
public class ExceptionControllerAdvice {

    /**
     * 表单提交数据校验异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handlerValidationException(MethodArgumentNotValidException e) {
        log.error("数据校验出现问题{},异常类型{}", e.getMessage(), e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> errorInfoMap = new HashMap<>();
        // 获取到全部字段校验错误
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            // 获取字段名
            String field = fieldError.getField();
            // 获取每一个字段校验错误信息
            String message = fieldError.getDefaultMessage();
            errorInfoMap.put(field, message);
        }
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(), BizCodeEnum.VALID_EXCEPTION.getMsg()).put("data", errorInfoMap);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handlerException(Throwable throwable) {
        throwable.printStackTrace();
        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION.getCode(), BizCodeEnum.UNKNOWN_EXCEPTION.getMsg());
    }


}
